var url = "ws://localhost:8080/websocket/test";
var webSocket = null;

$(function () {
    connect();
    $('#websocket').bind('click',function(){
        if(webSocket.readyState == 1){
            webSocket.send("hello");
        }else {
            webSocket.onclose();
            connect();
        }
    })
})

function connect() {
    if ('WebSocket' in window){
        $('#status').html("正在连接...").css("color","blue");
        //创建WebSocket连接
        webSocket = new WebSocket(url);
    }else {
        alert("您的浏览器不支持WebSocket");
    }

    webSocket.onopen = function(){
        $('#status').html("已连接").css("color","green")
    }
    webSocket.onmessage = function(e){
        console.log(e.data);
    }
    webSocket.onclose = function(e){
        $('#status').html("连接断开").css("color","blue");
    }
    webSocket.onerror = function(e){
        $('#status').html("连接失败").css("color","red");
    }

    window.onbeforeunload = function () {
        webSocket.close();
    }
}